package com.erpanderp.wam.usm.view.leave;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import org.primefaces.context.RequestContext;

import com.erpanderp.wam.adm.model.entity.HolidayCalendar;
import com.erpanderp.wam.adm.model.service.*;
import com.erpanderp.wam.adm.model.entity.Role;
import com.erpanderp.wam.tm.model.service.RRFDAO;
import com.erpanderp.wam.usm.model.entity.leave.EmployeeLeave;
import com.erpanderp.wam.usm.model.entity.leave.LeaveBalance;
import com.erpanderp.wam.usm.model.entity.leave.LeaveBalanceTracker;
import com.erpanderp.wam.usm.model.entity.leave.LeaveType;
import com.erpanderp.wam.usm.model.entity.leave.LeaveTypeRole;
import com.erpanderp.wam.usm.model.entity.projectandassignment.Project;

import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.EmployeeRole;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.EmployeeLeaveDAO;
import com.erpanderp.wam.usm.model.service.leave.LeaveBalanceDAO;
import com.erpanderp.wam.usm.model.service.leave.LeaveBalanceTrackerDAO;
import com.erpanderp.wam.usm.model.service.leave.LeaveTypeRoleDAO;

import com.erpanderp.wam.usm.model.service.leave.LeaveTypeDAO;
import com.erpanderp.wam.usm.model.service.projectandassignment.EmployeeProjectDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeRoleDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;
import com.itextpdf.text.log.SysoLogger;

import javax.swing.SwingWorker;

@ManagedBean
@ViewScoped
public class LeaveBalanceBean implements Serializable {

	private static final long serialVersionUID = 1L;

	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);
	HttpServletRequest request = (HttpServletRequest) FacesContext
			.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance()
			.getExternalContext().getContext();
	private WAMUser wamUser;
	private boolean detailsForLeave;
	private Map<String, Float> leaveBalances = new HashMap<String, Float>();
	private LeaveTypeDAO leaveTypeDAO;
	private Float slBalance;
	private Float plBalance;
	private Float clBalance;
	private Float whBalance;
	private Float ohBalance;
	private Float lopBalance;
	private Float compOffBalance;
	private int month;
	private int day;
	private int year;
	private LeaveBalance leaveBalance;
	private LeaveBalanceTracker leaveBalanceTracker;
	private EmployeeDAO employeeDAO;
	private EmployeeLeaveDAO employeeLeaveDAO;
	private LeaveBalanceTrackerDAO leaveBalanceTrackerDAO;
	private List<LeaveType> leaveTypes = new ArrayList<LeaveType>();
	private List<LeaveBalanceTracker> leaveBalanceTrackers = new ArrayList<LeaveBalanceTracker>();
	private List<LeaveBalance> leaveBalancesToBeAssigned = new ArrayList<LeaveBalance>();
	private List<LeaveBalanceTracker> leaveBalanceTrackersToBeCreated = new ArrayList<LeaveBalanceTracker>();
	Date date = new Date();
	SimpleDateFormat sdfMonth = new SimpleDateFormat("MMM");
	SimpleDateFormat sdfMonthInteger = new SimpleDateFormat("MM");
	SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfDay = new SimpleDateFormat("dd");
	private Employee reportingManager = new Employee();
	private String reportingManagerName;
	private String reportingManagerEmail;
	private String empName;
	private boolean detailsForConfirmLeave;
	private RRFDAO rrfDAO = new RRFDAO();
	private Map<String, Long> leaveTypesMap = new HashMap<String, Long>();
	private Long selectedLeaveTypeId;
	private EmployeeLeave employeeLeave = new EmployeeLeave();
	private Long noOfDays;
	private boolean FORM_VALID;
	private EmailUtil emailUtil;
	private LeaveType leaveType = new LeaveType();
	private String leaveCODE;
	private List<EmployeeLeave> employeeLeaves = new ArrayList<EmployeeLeave>();
	private List<EmployeeLeave> employeeLeavesCancellation = new ArrayList<EmployeeLeave>();
	private boolean renderEmployeeLeaves = false;
	private boolean renderEmployeeCacelledLeaves = false;
	private EmployeeLeave selectedEmployeeLeave = new EmployeeLeave();
	private EmployeeAndReportingDAO employeeAndReportingDAO;
	private EmployeeAndReporting employeeAndReporting;
	private boolean leaveCancelRequestApprovedAlready = true;
	private String leavesMonth;
	private List<Date> leaveDates = new ArrayList<Date>();
	private float selectedLeaveBalance;
	private boolean leaveBalanceFlag;
	private boolean sufficientLeaves;
	private float actualBalance;
	private boolean buttonRender = true;
	private List<LeaveBalance> leaveBalancesList = new ArrayList<LeaveBalance>();
	private LeaveBalanceDAO leaveBalanceDAO = new LeaveBalanceDAO();
	private boolean renderSLBalance = false;
	private boolean renderPLBalance = false;
	private boolean renderCLBalance = false;
	private boolean renderWHBalance = false;
	private boolean renderOHBalance = false;
	private LeaveTypeRoleDAO leaveTypeRoleDAO = new LeaveTypeRoleDAO();
	private LeaveTypeRole leaveTypeRole = new LeaveTypeRole();
	private List<LeaveTypeRole> leaveTypeListForRoles = new ArrayList<LeaveTypeRole>();
	private String assignedLeave;
	private boolean assignedSLLeaveFlag;
	private boolean assignedCLLeaveFlag;
	private boolean assignedWHLeaveFlag;
	private boolean assignedOHLeaveFlag;
	private boolean assignedPLLeaveFlag;
	private boolean assignedLOPLeaveFlag;
	private int columnCount = 0;
	private boolean LEAVETYPE_FORM_VALID;
	private boolean selectedLeaveBalanceRenderer;
	private String selectedLeaveType;
	private boolean renderApplyLeaveButton;
	private boolean renderLeaveBalanceNotification;
	private TimeZone defaultTimeZone = TimeZone.getDefault();
	private Map<String, Long> projectManagersMap = new HashMap<String, Long>();
	private List<Employee> leadEmployeesList = new ArrayList<Employee>();
	private Employee projectManager = new Employee();
	private EmployeeAndReporting changedReportingManager = new EmployeeAndReporting();
	private long approverId;
	private Employee approver;
	private Map<String, Long> approversMap = new HashMap<String, Long>();
	private EmployeeRoleDAO employeeRoleDAO = new EmployeeRoleDAO();
	private long noOfDaysBetweenFromDateToDate;
	private boolean IN_PROJECT;
	EmployeeProjectDAO employeeProjectDAO = new EmployeeProjectDAO();
	private List<Project> projects;
	private boolean CONFIRM_FORM_VALID;
	SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
	private String leaveFromToBeDisplayed;
	private String leaveToToBeDisplayed;
	private List<HolidayCalendar> holidaysList = new ArrayList<HolidayCalendar>();
	private boolean halfDayLeaveFlag;
    private float halfDay;
    private boolean checked;
    private float totalInprocessDays = 0;
    private float totalInprocessDaysPlusCurrentNoofDays = 0;
   
    
	public LeaveBalanceBean() {
		wamUser = (WAMUser) session
				.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);

		if (wamUser != null) {
			List<Employee> temp = new EmployeeAndReportingDAO()
					.getTimesheetApprovers(wamUser.getEmployee()
							.getEmployeeId());

			if (temp != null) {
				for (Employee employee : temp) {
					approversMap.put(
							employee.getFirstName()
									+ " "
									+ employee.getLastName()
									+ " ("
									+ employeeRoleDAO.getRoleByEmployeeId(
											employee.getEmployeeId())
											.getDisplayName() + ")", employee
									.getEmployeeId());
				}
			}
			date = new Date();
			leavesMonth = sdfMonth.format(date);
			leavesMonth = leavesMonth.toUpperCase();
			employeeAndReportingDAO = new EmployeeAndReportingDAO();
			employeeAndReporting = new EmployeeAndReporting();
			employeeDAO = new EmployeeDAO();
			employeeLeaveDAO = new EmployeeLeaveDAO();
			leaveTypeDAO = new LeaveTypeDAO();
			rrfDAO = new RRFDAO();
			reportingManager = new Employee();

			wamUser = (WAMUser) session
					.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
			setEmpName(wamUser.getEmployee().getFirstName());
			employeeAndReporting = employeeAndReportingDAO
					.getEmployeeReportingDetail(wamUser.getEmployee()
							.getEmployeeId());
			if (employeeAndReporting.getProjectManager() != null) {
				approver = employeeAndReporting.getProjectManager();
				approverId = employeeAndReporting.getProjectManager()
						.getEmployeeId();
			}
			projects = employeeProjectDAO.getAllProjects(wamUser.getEmployee()
					.getEmployeeId());

			setReportingManagerName(employeeAndReporting.getEmployee()
					.getFirstName());
			setReportingManagerEmail(employeeAndReporting.getEmployee()
					.getEmail());
			setDetailsForConfirmLeave(false);
			leaveTypeDAO = new LeaveTypeDAO();
			employeeLeaveDAO = new EmployeeLeaveDAO();
			/*
			 * LEAVES APPLIED
			 */
			employeeLeaves = employeeLeaveDAO
					.getAllAppliedLeavesByEmployeeID(wamUser.getEmployee()
							.getEmployeeId());
			if (employeeLeaves.size() > 0) {
				System.out.println("EMPLOYEELEAVES SIZE IS :"
						+ employeeLeaves.size());
				renderEmployeeLeaves = true;
			} else {
				System.out
						.println("LOGGED IN EMPLOYEE DIDNT APPLY THE LEAVES B4");
			}

			/*
			 * LEAVES FOR CANCELLATION
			 */
			employeeLeavesCancellation = employeeLeaveDAO
					.getAllCancellationLeavesByEmployeeID(wamUser.getEmployee()
							.getEmployeeId());
			if (employeeLeavesCancellation.size() > 0) {
				renderEmployeeCacelledLeaves = true;
			} else {

				System.out
						.println("LOGGED IN EMPLOYEE DIDNT REQUEST FOR LEAVE CANCELLATION B4");
			}
			leaveTypes = leaveTypeDAO.getLeaveTypes();
			for (LeaveType leaveType : leaveTypes) {
				leaveTypesMap.put(leaveType.getLeaveType(),
						leaveType.getLeaveTypeid());
			}

			leaveTypeRoleDAO = new LeaveTypeRoleDAO();
			System.out.println("<WAM USER FIRST NAME IS>:"
					+ wamUser.getEmployee().getFirstName());

			Role role = new EmployeeRoleDAO().getRoleByEmployeeId(wamUser
					.getEmployee().getEmployeeId());
			if (role != null)
				leaveTypeListForRoles = leaveTypeRoleDAO
						.getLeaveTypesListByRoleId(role.getRoleId());
			System.out.println("LEAVE TYPE LIST FOR ROLES SIZE IS"
					+ leaveTypeListForRoles.size());
			for (LeaveTypeRole leaveTypeRole : leaveTypeListForRoles) {
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.SICKLEAVE_TYPE)) {
					System.out.println("SL CAN BE USED");
					assignedLeave = CommonLookup.LEAVE_ASSIGNED;
					assignedSLLeaveFlag = true;
					columnCount++;
				} else {

				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.CASUALLEAVE_TYPE)) {
					System.out.println("CL CAN BE USED");
					assignedCLLeaveFlag = true;
					columnCount++;
				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.PRIVILIZEDLEAVE_TYPE)) {
					System.out.println("PL CAN BE USED");
					assignedPLLeaveFlag = true;
					columnCount++;
				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.OPTIONALLEAVE_TYPE)) {
					System.out.println("OH CAN BE USED");
					assignedOHLeaveFlag = true;
					columnCount++;
				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.WORKFROMHOME_TYPE)) {
					System.out.println("WH CAN BE USED");
					assignedWHLeaveFlag = true;
					columnCount++;
				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.LOSS_OF_PAY_TYPE)) {
					System.out.println("LOP CAN BE USED");
					assignedLOPLeaveFlag = true;
					columnCount++;
				}
				if (leaveTypeRole.getLeaveType().getLeaveType()
						.equals(CommonLookup.COMP_OF_TYPE)) {
					System.out.println("COMP OFF CAN BE USED");
					assignedLOPLeaveFlag = true;
					columnCount++;
				}
				System.out.println("COLUMN COUNT " + columnCount);
			}

			leaveBalances = leaveBalanceDAO.getLeaveBalances(wamUser
					.getEmployee().getEmployeeId());

			slBalance = leaveBalances.get(CommonLookup.SICKLEAVE_TYPE);
			plBalance = leaveBalances.get(CommonLookup.PRIVILIZEDLEAVE_TYPE);
			clBalance = leaveBalances.get(CommonLookup.CASUALLEAVE_TYPE);
			whBalance = leaveBalances.get(CommonLookup.WORKFROMHOME_TYPE);
			ohBalance = leaveBalances.get(CommonLookup.OPTIONALLEAVE_TYPE);
			lopBalance = leaveBalances.get(CommonLookup.LOSS_OF_PAY_TYPE);
			compOffBalance = leaveBalances.get(CommonLookup.COMP_OF_TYPE);
			System.out.println("=======SL BALANCE===== " + slBalance);
			System.out.println("LEAVE BALANCE IN LEAVE BEAN CONSTRUCTOR :"
					+ leaveBalances.size());

			holidaysList = new HolidayCalendarDAO().getHolidays();

		} else {
			ValidationUtil.gotoLoginPage();
		}

	}

	public void approverChanged(AjaxBehaviorEvent e) {
		System.out.println("APPROVER CHANGED BEHAVIOUR CALLED-------------->");
		approver = employeeDAO.getEmployeeByEmployeeId(approverId);
		employeeAndReporting.setProjectManager(approver);
		employeeAndReporting.getProjectManager().setEmail(approver.getEmail());
		System.out.println("EMPLOYEE AND REPORTINTG MANAGER EMAIL = === "
				+ approver.getEmail());
		setApproverForEmployeeLeave(approver);

	}

	public void setApproverForEmployeeLeave(Employee selectedApprover) {
		if (employeeLeave != null) {
			employeeLeave.setApprover(selectedApprover);
		} else {

		}
	}

	public String applyLeaveAction(ActionEvent e) throws ParseException {
		String localHost;
		String publicHost;
		boolean confirmLeaveBeforeApply = false;

		SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		// String fromDate = formatter.format(employeeLeave.getPeriodFrom());
		// String toDate = formatter.format(employeeLeave.getPeriodTo());
		System.out.println("IN APPLY LEAVE ACTION");
		validate();

		if (FORM_VALID) {
			leaveType = leaveTypeDAO.getLeaveTypeById(leaveType
					.getLeaveTypeid());
			if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)) {
				
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo() , employeeLeave.getPeriodFrom()));
				 confirmLeaveBeforeApply = true;
				}else{
					employeeLeave.setNoOfDays(halfDay);
					confirmLeaveBeforeApply = true;
				}
				
				
			} else if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.LOSS_OF_PAY_TYPE)) {
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo() , employeeLeave.getPeriodFrom()));
				 confirmLeaveBeforeApply = true;
				}else{
					employeeLeave.setNoOfDays(halfDay);
					confirmLeaveBeforeApply = true;
				}
				
				 
				
			}else if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.COMP_OF_TYPE)) {
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo() , employeeLeave.getPeriodFrom()));
				 confirmLeaveBeforeApply = true;
				}else{
					employeeLeave.setNoOfDays(halfDay);
					confirmLeaveBeforeApply = true;
				}
				
				
			}else {
				confirmLeaveBeforeApply = confirmLeaveBeforeApply();
			}
			if (confirmLeaveBeforeApply){
				
				if (employeeAndReportingDAO == null)
					employeeAndReportingDAO = new EmployeeAndReportingDAO();
				    employeeAndReporting = employeeAndReportingDAO.getEmployeeReportingDetail(wamUser.getEmployee().getEmployeeId());
				boolean emailSent = false;
				employeeLeave.setProject(employeeAndReporting.getProject());
				employeeLeave.setLeaveType(leaveType);
				leaveCODE = CommonLookup.getAutoGeneratedLeaveCODE(leaveType , wamUser.getEmployeeCode());
				System.out.println("LEAVE CODE IS----------------------------------- =" + leaveCODE);
				employeeLeave.setLeaveCode(leaveCODE);
				employeeLeave.setCreateDate(new Date());
				employeeLeave.setApprovalStatus(CommonLookup.LEAVE_INPROCESS_STATUS);
				employeeLeave.setStatus("ACTIVE");
				employeeLeave.setCreatedBy(wamUser.getEmployee().getFirstName());
				employeeLeave.setAppliedOn(new Date());
				employeeLeave.setEmployee(wamUser.getEmployee());
				employeeLeave.setAvailableContactNumber(employeeLeave.getEmployee().getTelephone());
				employeeLeave.setApprover(approver);
                if(checked){
                	employeeLeave.setHalfDayStatus(CommonLookup.HALFDAY_STATUS);
                }else{
                	employeeLeave.setHalfDayStatus(CommonLookup.FULLDAY_STATUS);
                }
				employeeLeaveDAO.employeeLeaveApply(employeeLeave);

				Map<String, String> hostsMap = WAMHostManager
						.getWAMHosts(context);
				String domainName = context.getInitParameter("domainName");
                emailUtil = new EmailUtil();

				if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {

					String[] to = { approver.getEmail() };
					emailUtil.setRecieverAddresses(to);
				} else {
					String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
					emailUtil.setRecieverAddresses(to);
				}

				String requestURL = "usm/leave/approveleave.html?leaveCODE="+ leaveCODE + "&EMPID="
						             + wamUser.getEmployee().getEmployeeCode();
				String privateLink = "http://"+ hostsMap.get(CommonLookup.PRIVATEHOST) + "/"
						              + domainName + "/" + requestURL;
				String publicLink = "http://"+ hostsMap.get(CommonLookup.PUBLICHOST) + "/"
						             + domainName + "/" + requestURL;

				String messageString = "Dear "
						+ approver.getFirstName()
						+ " "
						+ approver.getLastName()
						+ ",<br /><br />"
						+

						"<table border='0'>"
						+ "<tr> <td>Employee id </td><td> : </td><td>"
						+ wamUser.getEmployee().getEmployeeCode()
						+ " </td></tr>"
						+ "<tr> <td>Employee name</td><td> : </td> <td>"
						+ wamUser.getEmployee().getFirstName()
						+ "</td></tr>"
						+ "<tr> <td>Employee available contact number</td><td> : </td> <td>"
						+ employeeLeave.getEmployee().getTelephone()
						+ "</td></tr>"
						+ "<tr> <td>Available address</td><td> : </td> <td>"
						+ employeeLeave.getAvailableAddress() + "</td></tr>"
						+ "<tr> <td>Reason for leave</td><td> : </td> <td>"
						+ employeeLeave.getReason() + "</td></tr>"
						+ "</table><br/>"
						+ "<a style='color:#FF9933;font-weight: bold;' href=\""
						+ privateLink + "\">"
						+ "Please click here to approve/reject leave request"
						+ "</a /><br />"
						+ "(Employees who are in Hyderabad office)"
						+ "<br /><br />"
						+ "<a style='color:#FF9933;font-weight: bold;' href=\""
						+ publicLink + "\">"
						+ "Please click here to approve/reject leave request"
						+ "</a /><br />" + "(out side Hyderabad office)"
						+ "<br /><br />" +

						"Thanks & Regards, <br />"
						+ CommonLookup.WAM_DEVTEAM_SIGNATURE;
				
				
				emailUtil.setMessage(messageString);
				
				emailUtil.setSenderEmail("podquick@erpanderp.com","WAM - Dev Team");
				emailUtil.setSubject(wamUser.getEmployee().getFirstName()
						+ " (" + leaveCODE + ") " + " Leave Request");

				RequestContext.getCurrentInstance().addPartialUpdateTarget(
						"leaveBalanceForm");
				RequestContext.getCurrentInstance().execute(
						"applyLeaveWidget.hide();");
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								" Leave Applied successfully.", ""));
				employeeLeaves = employeeLeaveDAO
						.getAllAppliedLeavesByEmployeeID(wamUser.getEmployee()
								.getEmployeeId());
				SwingWorker worker = new SwingWorker<String, Object>() {

					@Override
					protected String doInBackground() throws Exception {
						// TODO Auto-generated method stub

						emailUtil.processAndSendEmail();
						return null;
					}

					@Override
					protected void done() {
						// TODO Auto-generated method stub
						System.out.println("MAIL SENT");
						// super.done();
					}
				};
				worker.execute();

				employeeLeave = new EmployeeLeave();
				checked = false;
				leaveType = new LeaveType();

			} else {
				RequestContext.getCurrentInstance().execute(
						"applyLeaveWidget.show();");
				sufficientLeaves = true;
				//FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "You do not have sufficient balance.", ""));
			}

		} else {
			// System.out.println("FORM INVALID");
			RequestContext.getCurrentInstance().execute(
					"applyLeaveWidget.show();");
		}

		return "leavebalance";
	}

	public float getBalance() {

		LeaveBalanceDAO leaveBalanceDAO = new LeaveBalanceDAO();
		System.out.println("VALUECHANGE EVENT IS TRIGGERED:");
		float balance = 0L;
		//LeaveBalance leaveBalance = new LeaveBalance();
		System.out
				.println("BEFORE LEAVE SELECTED SELECTED LEAVE BALANCE RENDERER ="
						+ selectedLeaveBalanceRenderer);
		if ((leaveType != null) && !(leaveType.equals(""))) {

			selectedLeaveBalanceRenderer = true;
			System.out
					.println("AFTER LEAVE SELECTED SELECTED LEAVE BALANCE RENDERER ="
							+ selectedLeaveBalanceRenderer);
			System.out.println("SELECTED LEAVETYPE ="
					+ leaveType.getLeaveTypeid());
			leaveBalance = leaveBalanceDAO
					.getActualLeaveBalanceByLeaveTypeIdAndEmployeeId(leaveType
							.getLeaveTypeid(), wamUser.getEmployee()
							.getEmployeeId());
			if (leaveBalance != null && leaveBalance.getBalance() != 0.0) {
				selectedLeaveBalance = leaveBalance.getBalance();

				System.out.println("SELECTED LEAVE BALANCE----------> = "
						+ selectedLeaveBalance);
				if (leaveBalance != null && leaveBalance.getBalance() >= 0.5) {

					balance = leaveBalance.getBalance();

				}

			}
		} else {
			selectedLeaveBalanceRenderer = false;
		}
		System.out
				.println("SELECTED LEAVE BALANCE RENDERER IS "
						+ selectedLeaveBalanceRenderer);
		return balance;

	}

	public void getBalanceListner(AjaxBehaviorEvent e) {

		System.out.println("IN getBalanceListner()...................");
		getBalance();

	}

	public boolean confirmLeaveBeforeApply() {
		System.out.println("-----------IN CONFIEM LEAVE ACTION-------------");
		boolean CONFIRM_LEAVE = true;

		LeaveType selectedLeaveType = null;
        if(!checked){
		 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo(),employeeLeave.getPeriodFrom()));
        }
        	

		actualBalance = getBalance();

		System.out.println("ACTUAL BALANCE IS " + actualBalance);
		System.out.println("APPLIED DAYS BALANCE IS "
				+ employeeLeave.getNoOfDays());
        
		if ((employeeLeave.getNoOfDays()) <= actualBalance) {
			RequestContext.getCurrentInstance().execute(
					"applyLeaveWidget.show();");
			System.out.println("HAVING SUFFICIENT BALANCE");
            if(validateBalance()){
            
			 sufficientLeaves = false;
			
            }else{
            	 CONFIRM_LEAVE = false;
            	FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "You dont have enough balance.You have "+totalInprocessDays+" leaves to be approved.", ""));
            }
		} else {
			
			
			leaveType = new LeaveTypeDAO().getLeaveTypeById(leaveType
					.getLeaveTypeid());
			if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)) {
				System.out.println("SELECTED LEAVE TYPE IS WH----> "
						+ leaveType.getLeaveType());
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo() , employeeLeave.getPeriodFrom()));
				}
				
				sufficientLeaves = false;
			} else if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.LOSS_OF_PAY_TYPE)) {
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo(), employeeLeave.getPeriodFrom()));
				}
				
				sufficientLeaves = false;
				System.out.println("SELECTED LEAVE TYPE IS LOP----> "+ leaveType.getLeaveType());
			} else if (leaveType != null && leaveType.getLeaveType().equals(CommonLookup.COMP_OF_TYPE)) {
				if(!checked){
				 employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo(), employeeLeave.getPeriodFrom()));
				}
				
				sufficientLeaves = false;
				System.out.println("SELECTED LEAVE TYPE IS COMP OFF----> "
						+ leaveType.getLeaveType());
			} else if(leaveType != null && !leaveType.getLeaveType().equals(CommonLookup.OPTIONALLEAVE_TYPE)){
				if(validateBalance()){
				if(!checked){
					System.out.println("HALF DAY NOT CHECKED");
				employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo(), employeeLeave.getPeriodFrom()));
				
					if(employeeLeave.getNoOfDays() > actualBalance){
						CONFIRM_LEAVE = false;
						RequestContext.getCurrentInstance().execute(
								"applyLeaveWidget.show();");
						sufficientLeaves = true;
						FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "You do not have enough balance.", ""));
						buttonRender = false;
						System.out.println("DONT HAVING SUFFICIENT BALANCE");	
					}
				}else{
					System.out.println("HALF DAY CHECKED");
					System.out.println("ACTUAL BALANCE ="+actualBalance);
					if(actualBalance >= 0.5){
					 employeeLeave.setNoOfDays(halfDay);
					 sufficientLeaves = false;
					}else{
						System.out.println("ACTUAL BALANCE IS LT 0.5="+actualBalance);
						sufficientLeaves = true;
						CONFIRM_LEAVE = false;
						FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "You do not have enough balance.", ""));
					}
					
				}
				
			}else{
				CONFIRM_LEAVE = false;
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "You dont have enough balance.You have "+totalInprocessDays+" leaves to be approved.", ""));
			}

				
			}
			
		}
        
		RequestContext.getCurrentInstance().execute("applyLeaveWidget.show();");

		return CONFIRM_LEAVE;

	}
	
	public boolean validateBalance(){
		totalInprocessDays = 0;
		boolean BALANCE_VALID = true;
		List<EmployeeLeave> employeeLeaves = new ArrayList<EmployeeLeave>();
		EmployeeLeaveDAO employeeLeaveDAO = new EmployeeLeaveDAO();
		LeaveBalanceDAO leaveBalanceDAO = new LeaveBalanceDAO();
		employeeLeaves = employeeLeaveDAO.getEmployeeLeavesByInProcessEmployeeIdAndLeaveTypeId(wamUser.getEmployee().getEmployeeId(),CommonLookup.LEAVE_INPROCESS_STATUS,leaveType.getLeaveTypeid());
		System.out.println("INPROCESS LIST SIZE ="+employeeLeaves.size());
		for(EmployeeLeave employeeLeave : employeeLeaves){
			totalInprocessDays = totalInprocessDays+employeeLeave.getNoOfDays();
			System.out.println("ASSING COUNT ="+totalInprocessDays);
		}
		System.out.println("TOTAL INPROCESS DAYS ="+totalInprocessDays);
		totalInprocessDaysPlusCurrentNoofDays = totalInprocessDays+employeeLeave.getNoOfDays();
		System.out.println("TOTAL INPROCESS DAYS WITH APPLYING LEAVES COUNT ="+totalInprocessDaysPlusCurrentNoofDays);
		LeaveBalance leaveBalance = leaveBalanceDAO.getActualLeaveBalanceByLeaveTypeIdAndEmployeeId(leaveType.getLeaveTypeid(), wamUser.getEmployee().getEmployeeId());
		if(leaveBalance != null && (leaveBalance.getBalance() >= 1.0 && leaveBalance.getBalance() >= employeeLeave.getNoOfDays())){
		if(leaveBalance != null && leaveBalance.getBalance() >= totalInprocessDaysPlusCurrentNoofDays){
			
		}else{
			BALANCE_VALID = false;
		}
		}else{
			
		}
		return BALANCE_VALID;
		
		
	}


	public String closeApplyLeaveDialog() {
		System.out.println("IN CLOSE DIALOGE");
		checked = false;
		halfDayLeaveFlag = false;
		halfDay =  (float) 0.0;
		sufficientLeaves = false;
		leaveType = new LeaveType();
		employeeLeave = new EmployeeLeave();

		RequestContext.getCurrentInstance().execute("applyLeaveWidget.hide();");
		return "leavebalance";
	}

	public String closeCancelLeaveDialog() {
		System.out.println("IN CLOSE CANCEL DIALOGE");

		selectedEmployeeLeave = new EmployeeLeave();
		RequestContext.getCurrentInstance().addPartialUpdateTarget("cancelLeaveWidget");
		RequestContext.getCurrentInstance().execute("cancelLeaveWidget.hide();");
		return "leavebalance";
	}

	public void closeCancelLeaveCheckStatusDialog() {
		RequestContext.getCurrentInstance().execute("cancelledLeavesDialog.hide();");

	}

	public void noOfDaysListener(ActionEvent a) throws ParseException {
		System.out.println("NO OF DAYS CHANGED BEHAVIOUR CALLED-------------->");

		if (a.getComponent().getId().equals("Confirm")) {
			confirmValidate();
			if (CONFIRM_FORM_VALID) {
				System.out.println("CONFIRM FORM VALIDATED------------------");
				employeeLeave.setNoOfDays(daysBetween(employeeLeave.getPeriodTo(),employeeLeave.getPeriodFrom()));
				leaveFromToBeDisplayed = sdf.format(employeeLeave.getPeriodFrom());
				leaveToToBeDisplayed = sdf.format(employeeLeave.getPeriodTo());
				confirmLeaveBeforeApply();
			
			} else {

			}
		}

	}
	

	public void halfDayStatusListner(AjaxBehaviorEvent a) throws ParseException {
		String summary = checked ? "Checked" : "Unchecked";  
		System.out.println("CHECKED SUMMARY "+summary);
		System.out.println("HALF DAY LISTNER");
	    EmployeeLeave employeeHalfDayLeave = new EmployeeLeave();		
		if(summary.equals("Checked")){
        	halfDayLeaveFlag = true;
			halfDay =  (float) 0.5;	
			employeeLeave.setNoOfDays(halfDay);
			System.out.println("IF");		
		}else{			
			halfDayLeaveFlag = false;
			halfDay =  (float) 0.0;	
			employeeLeave.setNoOfDays(halfDay);
			System.out.println("ELSE");			
		}		
	}

	public float daysBetween(Date max, Date min) {
		System.out.println("IN DAYSBETWEEN METHOD");
		System.out.println("MAX DATE :" + max);
		System.out.println("MIN DATE :" + min);
		if(!checked){
		 return ((max.getTime() - min.getTime()) / 86400000) + 1;
		}else{
			 halfDay =  (float) 0.5;	
		     return halfDay;
		}
	}

	public String leaveCancellationByEmployee() {
		String localHost;
		String publicHost;
		System.out.println(" IN LEAVE CANCELLATION BY EMPLOYEE ");
		validateLeaveCancelRequest();
		if (FORM_VALID) {
			String messageString = null;
			employeeLeave.setReasonForCancel(selectedEmployeeLeave.getReasonForCancel());
			employeeLeave.setLeaveCancellationDate(new Date());
			System.out.println("SELECTED EMPLOYEE LEAVE STATUS=============:"+ selectedEmployeeLeave.getApprovalStatus());

			Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			String domainName = context.getInitParameter("domainName");

			emailUtil = new EmailUtil();

			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {

				String[] to = { employeeAndReporting.getProjectManager()
						.getEmail() };
				emailUtil.setRecieverAddresses(to);
			} else {
				String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
				emailUtil.setRecieverAddresses(to);
			}

			String requestURL = "usm/leave/approvecancelledleave.html?leaveCODE="
					+ selectedEmployeeLeave.getLeaveCode()
					+ "&EMPID="
					+ wamUser.getEmployee().getEmployeeCode();
			String privateLink = "http://"
					+ hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName
					+ "/" + requestURL;
			String publicLink = "http://"
					+ hostsMap.get(CommonLookup.PUBLICHOST) + "/" + domainName
					+ "/" + requestURL;

			System.out.println("LEAVE INPROCESS STATUS="
					+ selectedEmployeeLeave.getApprovalStatus());
			if (selectedEmployeeLeave.getApprovalStatus().equals(
					CommonLookup.LEAVE_INPROCESS_STATUS)) {

				messageString = "Dear "
						+ employeeAndReporting.getProjectManager()
								.getFirstName()
						+ " "
						+ employeeAndReporting.getProjectManager()
								.getLastName()
						+ ",<br /><br />"
						+

						"<table border='0'>"
						+ "<tr> <td>Employee id </td><td> : </td><td>"
						+ wamUser.getEmployee().getEmployeeCode()
						+ " </td></tr>"
						+ "<tr> <td>Employee name</td><td> : </td> <td>"
						+ wamUser.getEmployee().getFirstName()
						+ "</td></tr>"
						+ "<tr> <td>Employee available contact number</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getEmployee().getTelephone()
						+ "</td></tr>"
						+ "<tr> <td>Available address</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getAvailableAddress()
						+ "</td></tr>"
						+ "<tr> <td>Reason for leave cancellation</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getReasonForCancel()
						+ "</td></tr>" + "</table><br/>" +

						"Thanks & Regards, <br />"
						+ CommonLookup.WAM_DEVTEAM_SIGNATURE;

			} else {
				System.out.println("(EMP CAN APPLY FOR CANCELLATION");
				messageString = "Dear "
						+ employeeAndReporting.getProjectManager()
								.getFirstName()
						+ " "
						+ employeeAndReporting.getProjectManager()
								.getLastName()
						+ ",<br /><br />"
						+

						"<table border='0'>"
						+ "<tr> <td>Employee id </td><td> : </td><td>"
						+ wamUser.getEmployee().getEmployeeCode()
						+ " </td></tr>"
						+ "<tr> <td>Employee name</td><td> : </td> <td>"
						+ wamUser.getEmployee().getFirstName()
						+ "</td></tr>"
						+ "<tr> <td>Employee available contact number</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getEmployee().getTelephone()
						+ "</td></tr>"
						+ "<tr> <td>Available address</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getAvailableAddress()
						+ "</td></tr>"
						+ "<tr> <td>Reason for leave cancellation</td><td> : </td> <td>"
						+ selectedEmployeeLeave.getReasonForCancel()
						+ "</td></tr>"
						+ "</table><br/>"
						+ "<a style='color:#FF9933;font-weight: bold;' href=\""
						+ privateLink
						+ "\">"
						+ "Please click here to approve/reject leave cancellation request"
						+ "</a /><br />"
						+ "(Employees who are in Hyderabad office)"
						+ "<br /><br />"
						+

						"<a style='color:#FF9933;font-weight: bold;' href=\""
						+ publicLink
						+ "\">"
						+ "Please click here to approve/reject leave cancellation request"
						+ "</a /><br />" + "(out side Hyderabad office)"
						+ "<br /><br />" +

						"Thanks & Regards, <br />"
						+ CommonLookup.WAM_DEVTEAM_SIGNATURE;

			}
			if (selectedEmployeeLeave.getApprovalStatus().equals(CommonLookup.LEAVE_INPROCESS_STATUS)) {
				System.out.println("-----------CANCEL LEAVE REQUEST HIMSELF--------");
				selectedEmployeeLeave.setCancellationAppliedOn(new Date());
				selectedEmployeeLeave.setApprovalStatus(CommonLookup.LEAVE_EMP_CANCELLED_STATUS);
				RequestContext.getCurrentInstance().execute("cancelLeaveWidget.hide();");
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," Leave cancelled successfully.", ""));

			} else if (selectedEmployeeLeave.getApprovalStatus().equals(CommonLookup.LEAVE_APPROVED_STATUS)) {
				System.out.println("++++++++++++APPROVED LEAVE REQUESTED TO CANCEL++++++++++");
				selectedEmployeeLeave.setApprovalStatus(CommonLookup.LEAVE_CANCELLATION_INPROCESS_STATUS);
				RequestContext.getCurrentInstance().execute("cancelLeaveWidget.hide();");
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," Leave cancel request sent successfully.",""));
			} else {
				System.out.println("============APPROVAL STATUS IS CANCELLED===========");

			}
			employeeLeaveDAO.leaveCancelRequestByEmployee(selectedEmployeeLeave);
			
			emailUtil.setMessage(messageString);
			
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
			emailUtil.setSubject(wamUser.getEmployee().getFirstName() + " ("+ selectedEmployeeLeave.getLeaveCode() + ") "
					             + " Leave Cancel Request");

			RequestContext.getCurrentInstance().addPartialUpdateTarget("leaveBalanceForm");
		
			SwingWorker worker = new SwingWorker<String, Object>() {

				@Override
				protected String doInBackground() throws Exception {
					// TODO Auto-generated method stub

					emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
					// TODO Auto-generated method stub
					System.out.println("MAIL SENT");
					// super.done();
				}
			};
			worker.execute();

			employeeLeave = new EmployeeLeave();

		} else {
			
			RequestContext.getCurrentInstance().execute("cancelLeaveWidget.show();");
		}
		return "leavebalance";
	}

	public boolean validate() throws ParseException {
		sufficientLeaves = false;

		List<EmployeeLeave> employeeLeaves = new ArrayList<EmployeeLeave>();
		Calendar cal = new GregorianCalendar();
		List<Date> approvedLeaveDates = new ArrayList<Date>();
		List<Date> inProcessLeaveDates = new ArrayList<Date>();
		employeeDAO = new EmployeeDAO();
		employeeLeaveDAO = new EmployeeLeaveDAO();
		System.out.println("IN VALIDATE METHOD");
		FORM_VALID = true;
		System.out.println("LEAVETYPE ID = "
				+ leaveType.getLeaveTypeid().toString());
		if (ValidationUtil.isEmpty(
				(leaveType.getLeaveTypeid() != 0) ? leaveType.getLeaveTypeid().toString() : null, "Leave Type", null, 
						FacesContext.getCurrentInstance()) != null) {
			System.out.println("LEAVE TYPE IS EMPTY");

			FORM_VALID = false;

		}
		if (leaveType.getLeaveTypeid() != 0) {
			LeaveType leaveTypeForProject = new LeaveTypeDAO().getLeaveTypeById(leaveType.getLeaveTypeid());
				if (leaveTypeForProject != null && leaveTypeForProject.getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)) {
				if (employeeAndReporting.getProject() != null && !employeeAndReporting.getProject().equals(
			            CommonLookup.PROJECT_KA) && projects != null && projects.size() > 0) {

				} else {
					FORM_VALID = false;
					FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,"Work From Home leaves for those who are on project",""));
					
				}
			}
		}

		if (ValidationUtil.isEmpty((employeeLeave.getPeriodFrom() != null) ? employeeLeave.getPeriodFrom().toString() : null, 
				"Leave From", null,FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("LEAVE FORM IS EMPTY");
		}
		if (ValidationUtil.isEmpty(
				(employeeLeave.getPeriodTo() != null) ? employeeLeave
						.getPeriodTo().toString() : null, "Leave To", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("LEAVE TO IS EMPTY");
		}

		if (ValidationUtil.isEmpty(employeeLeave.getAvailableAddress(),
				"Available Address", null, FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("AVAILABLE ADDRESS IS EMPTY");
		}
		if (ValidationUtil.isEmpty(employeeLeave.getReason(),
				"Reason For Leave", null, FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("REASON FOR LEAVE IS EMPTY");
		}
		System.out.println("EMPLOYEE LEAVE PERIOD FROM :"
				+ employeeLeave.getPeriodFrom());
		System.out.println("EMPLOYEE LEAVE PERIOD TO :"
				+ employeeLeave.getPeriodTo());
		Date periodFrom = employeeLeave.getPeriodFrom() != null ? employeeLeave
				.getPeriodFrom() : null;
		Date periodTo = employeeLeave.getPeriodTo() != null ? employeeLeave
				.getPeriodTo() : null;

		if (periodFrom != null && periodTo != null) {

			String fromDate = sdf.format(periodFrom);
			String toDate = sdf.format(periodTo);

			Calendar calendarForSunday = Calendar.getInstance();
			calendarForSunday.setTime(periodFrom);

			Calendar calendarForSaturday = Calendar.getInstance();
			calendarForSaturday.setTime(periodTo);

			Date date1 = sdf.parse(fromDate);
			Date date2 = sdf.parse(toDate);
			if (date1.compareTo(date2) > 0) {
				FORM_VALID = false;
				System.out.println("FROMDATE is after TODATE");
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
								" From-date should not be more than To-date",""));
			} 

			approvedLeaveDates = new EmployeeLeaveDAO().getApprovedEmployeeLeaveDatesBy(periodFrom, periodTo, wamUser.getEmployee().getEmployeeId());
			inProcessLeaveDates = new EmployeeLeaveDAO().getInprocessEmployeeLeaveDatesBy(periodFrom, periodTo, wamUser.getEmployee().getEmployeeId());
			if(!checked){
				if ((approvedLeaveDates != null && approvedLeaveDates.size() == 2) || (inProcessLeaveDates != null && inProcessLeaveDates.size() == 2) || (approvedLeaveDates.size()+inProcessLeaveDates.size() == 2)) {
				FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN," Leave has taken already in this period", ""));
			} 
			}else{
				if(periodFrom.equals(periodTo)){
					System.out.println("TOTAL APPLIED DAYS ="+approvedLeaveDates.size()+inProcessLeaveDates.size());
					if ((approvedLeaveDates != null && approvedLeaveDates.size() == 2) || (inProcessLeaveDates != null && inProcessLeaveDates.size() == 2) || (approvedLeaveDates.size()+inProcessLeaveDates.size() == 2)) {
					FORM_VALID = false;
					FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN," Leave has taken already in this period", ""));
				}
				}else{

					System.out.println("DATES SHOULD NOT EQUAL FOR HALF DAY LEAVE");
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "From-date To-date should be same.", ""));
					FORM_VALID = false;
				}
			}
			
			
		}

		return FORM_VALID;
	}

	public boolean confirmValidate() throws ParseException {
		CONFIRM_FORM_VALID = true;
		List<Date> approvedLeaveDates = new ArrayList<Date>();
		List<Date> inProcessLeaveDates = new ArrayList<Date>();
		if (ValidationUtil.isEmpty(
				(leaveType.getLeaveTypeid() != 0) ? leaveType.getLeaveTypeid()
						.toString() : null, "Leave Type", null, FacesContext
						.getCurrentInstance()) != null) {
			System.out.println("LEAVE TYPE IS EMPTY");

			CONFIRM_FORM_VALID = false;

		}
		if (leaveType.getLeaveTypeid() != 0) {
			LeaveType leaveTypeForProject = new LeaveTypeDAO().getLeaveTypeById(leaveType.getLeaveTypeid());
			System.out.println("SELECTED LEAVE TYPE "	+ selectedLeaveType);
			if (leaveTypeForProject != null && leaveTypeForProject.getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)) {
				if (employeeAndReporting.getProject() != null && !employeeAndReporting.getProject().equals(
								CommonLookup.PROJECT_KA) && projects != null
						&& projects.size() > 0) {
					System.out.println("WAM USER IN PROJECT-------------------------->");

				} else {
					CONFIRM_FORM_VALID = false;
					FacesContext
							.getCurrentInstance()
							.addMessage(
									null,
									new FacesMessage(
											FacesMessage.SEVERITY_WARN,
											"Work From Home leaves for those who are on project",
											""));
					System.out.println("WAM USER NOT IN PROJECT");
				}
			}
		}

		if (ValidationUtil.isEmpty(
				(employeeLeave.getPeriodFrom() != null) ? employeeLeave
						.getPeriodFrom().toString() : null, "Leave From", null,
				FacesContext.getCurrentInstance()) != null) {
			CONFIRM_FORM_VALID = false;
			System.out.println("CONFIRM LEAVE FORM IS EMPTY");
		}
		if (ValidationUtil.isEmpty(
				(employeeLeave.getPeriodTo() != null) ? employeeLeave
						.getPeriodTo().toString() : null, "Leave To", null,
				FacesContext.getCurrentInstance()) != null) {
			CONFIRM_FORM_VALID = false;
			System.out.println("CONFIRM LEAVE TO IS EMPTY");
		}
		System.out.println("EMPLOYEE LEAVE PERIOD FROM :"
				+ employeeLeave.getPeriodFrom());
		System.out.println("EMPLOYEE LEAVE PERIOD TO :"
				+ employeeLeave.getPeriodTo());
		Date periodFrom = employeeLeave.getPeriodFrom() != null ? employeeLeave
				.getPeriodFrom() : null;
		Date periodTo = employeeLeave.getPeriodTo() != null ? employeeLeave
				.getPeriodTo() : null;

		if (periodFrom != null && periodTo != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			String fromDate = sdf.format(periodFrom);
			String toDate = sdf.format(periodTo);

			Calendar calendarForSunday = Calendar.getInstance();
			calendarForSunday.setTime(periodFrom);

			Calendar calendarForSaturday = Calendar.getInstance();
			calendarForSaturday.setTime(periodTo);

			Date date1 = sdf.parse(fromDate);
			Date date2 = sdf.parse(toDate);
			if (date1.compareTo(date2) > 0) {
				CONFIRM_FORM_VALID = false;
				System.out.println("FROMDATE is after TODATE");
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								" From-date should not be more than To-date",
								""));
			}
			System.out.println("PERIOD FROM =" + periodFrom);
			System.out.println("PERIOD TO =" + periodTo);
			System.out.println("B4 METHOD CALLING");
			approvedLeaveDates = new EmployeeLeaveDAO().getApprovedEmployeeLeaveDatesBy(periodFrom, periodTo, wamUser.getEmployee().getEmployeeId());
			inProcessLeaveDates = new EmployeeLeaveDAO().getInprocessEmployeeLeaveDatesBy(periodFrom, periodTo, wamUser.getEmployee().getEmployeeId());
			if(!checked){
				if ((approvedLeaveDates != null && approvedLeaveDates.size() > 0) || (inProcessLeaveDates != null && inProcessLeaveDates.size() > 0)) {
				CONFIRM_FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN," Leave has taken already in this period", ""));
			}
			}else{
				if(periodFrom.equals(periodTo)){
					System.out.println("TOTAL APPLIED DAYS ="+approvedLeaveDates.size()+inProcessLeaveDates.size());
				if ((approvedLeaveDates != null && approvedLeaveDates.size() == 2) || (inProcessLeaveDates != null && inProcessLeaveDates.size() == 2) || (approvedLeaveDates.size()+inProcessLeaveDates.size() == 2)) {
					CONFIRM_FORM_VALID = false;
					FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN," Leaves has taken already in this period", ""));
				}
				}else{
					System.out.println("DATES ARE NOT EQUAL FOR HALF DAY LEAVE");
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "From-date To-date should be same.", ""));
					CONFIRM_FORM_VALID = false;
				}
			}
			
			
			

		}
		return CONFIRM_FORM_VALID;
	}

	public boolean validateLeaveCancelRequest() {

		FORM_VALID = true;
		if (ValidationUtil.isEmpty(selectedEmployeeLeave.getReasonForCancel(),
				"Reason for leave cancellation", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("REASON FOR CANCEL LEAVE IS EMPTY");
		}
		return FORM_VALID;

	}

	public String redirectApplyLeave() {
		System.out.println("APPLY LEAVE GOT HIT");
		return "applyleave";
	}

	// GETTERS AND SETTERS

	public boolean isDetailsForLeave() {
		return detailsForLeave;
	}

	public void setDetailsForLeave(boolean detailsForLeave) {
		this.detailsForLeave = detailsForLeave;
	}

	public LeaveTypeDAO getLeaveTypeDAO() {
		return leaveTypeDAO;
	}

	public void setLeaveTypeDAO(LeaveTypeDAO leaveTypeDAO) {
		this.leaveTypeDAO = leaveTypeDAO;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public Map<String, Float> getLeaveBalances() {
		return leaveBalances;
	}

	public void setLeaveBalances(Map<String, Float> leaveBalances) {
		this.leaveBalances = leaveBalances;
	}

	public Float getSlBalance() {
		return slBalance;
	}

	public void setSlBalance(Float slBalance) {
		this.slBalance = slBalance;
	}

	public Float getPlBalance() {
		return plBalance;
	}

	public void setPlBalance(Float plBalance) {
		this.plBalance = plBalance;
	}

	public Float getClBalance() {
		return clBalance;
	}

	public void setClBalance(Float clBalance) {
		this.clBalance = clBalance;
	}

	public Float getWhBalance() {
		return whBalance;
	}

	public void setWhBalance(Float whBalance) {
		this.whBalance = whBalance;
	}

	public Float getOhBalance() {
		return ohBalance;
	}

	public void setOhBalance(Float ohBalance) {
		this.ohBalance = ohBalance;
	}

	public EmployeeDAO getEmployeeDAO() {
		return employeeDAO;
	}

	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	public List<LeaveBalanceTracker> getLeaveBalanceTrackers() {
		return leaveBalanceTrackers;
	}

	public void setLeaveBalanceTrackers(
			List<LeaveBalanceTracker> leaveBalanceTrackers) {
		this.leaveBalanceTrackers = leaveBalanceTrackers;
	}

	public List<LeaveBalance> getLeaveBalancesToBeAssigned() {
		return leaveBalancesToBeAssigned;
	}

	public void setLeaveBalancesToBeAssigned(
			List<LeaveBalance> leaveBalancesToBeAssigned) {
		this.leaveBalancesToBeAssigned = leaveBalancesToBeAssigned;
	}

	public LeaveBalance getLeaveBalance() {
		return leaveBalance;
	}

	public void setLeaveBalance(LeaveBalance leaveBalance) {
		this.leaveBalance = leaveBalance;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public LeaveBalanceTracker getLeaveBalanceTracker() {
		return leaveBalanceTracker;
	}

	public void setLeaveBalanceTracker(LeaveBalanceTracker leaveBalanceTracker) {
		this.leaveBalanceTracker = leaveBalanceTracker;
	}

	public List<LeaveBalanceTracker> getLeaveBalanceTrackersToBeCreated() {
		return leaveBalanceTrackersToBeCreated;
	}

	public void setLeaveBalanceTrackersToBeCreated(
			List<LeaveBalanceTracker> leaveBalanceTrackersToBeCreated) {
		this.leaveBalanceTrackersToBeCreated = leaveBalanceTrackersToBeCreated;
	}

	public LeaveBalanceTrackerDAO getLeaveBalanceTrackerDAO() {
		return leaveBalanceTrackerDAO;
	}

	public void setLeaveBalanceTrackerDAO(
			LeaveBalanceTrackerDAO leaveBalanceTrackerDAO) {
		this.leaveBalanceTrackerDAO = leaveBalanceTrackerDAO;
	}

	public String getReportingManagerName() {
		return reportingManagerName;
	}

	public void setReportingManagerName(String reportingManagerName) {
		this.reportingManagerName = reportingManagerName;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public boolean isDetailsForConfirmLeave() {
		return detailsForConfirmLeave;
	}

	public void setDetailsForConfirmLeave(boolean detailsForConfirmLeave) {
		this.detailsForConfirmLeave = detailsForConfirmLeave;
	}

	public Map<String, Long> getLeaveTypesMap() {
		return leaveTypesMap;
	}

	public void setLeaveTypesMap(Map<String, Long> leaveTypesMap) {
		this.leaveTypesMap = leaveTypesMap;
	}

	public Long getSelectedLeaveTypeId() {
		return selectedLeaveTypeId;
	}

	public void setSelectedLeaveTypeId(Long selectedLeaveTypeId) {
		this.selectedLeaveTypeId = selectedLeaveTypeId;
	}

	public EmployeeLeave getEmployeeLeave() {
		return employeeLeave;
	}

	public void setEmployeeLeave(EmployeeLeave employeeLeave) {
		this.employeeLeave = employeeLeave;
	}

	public Long getNoOfDays() {
		return noOfDays;
	}

	public void setNoOfDays(Long noOfDays) {
		this.noOfDays = noOfDays;
	}

	public boolean isFORM_VALID() {
		return FORM_VALID;
	}

	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public EmailUtil getEmailUtil() {
		return emailUtil;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public LeaveType getLeaveType() {
		return leaveType;
	}

	public void setLeaveType(LeaveType leaveType) {
		this.leaveType = leaveType;
	}

	public String getLeaveCODE() {
		return leaveCODE;
	}

	public void setLeaveCODE(String leaveCODE) {
		this.leaveCODE = leaveCODE;
	}

	public String getReportingManagerEmail() {
		return reportingManagerEmail;
	}

	public void setReportingManagerEmail(String reportingManagerEmail) {
		this.reportingManagerEmail = reportingManagerEmail;
	}

	public List<EmployeeLeave> getEmployeeLeaves() {
		return employeeLeaves;
	}

	public void setEmployeeLeaves(List<EmployeeLeave> employeeLeaves) {
		this.employeeLeaves = employeeLeaves;
	}

	public boolean isRenderEmployeeLeaves() {
		return renderEmployeeLeaves;
	}

	public void setRenderEmployeeLeaves(boolean renderEmployeeLeaves) {
		this.renderEmployeeLeaves = renderEmployeeLeaves;
	}

	public EmployeeLeave getSelectedEmployeeLeave() {
		return selectedEmployeeLeave;
	}

	public void setSelectedEmployeeLeave(EmployeeLeave selectedEmployeeLeave) {
		this.selectedEmployeeLeave = selectedEmployeeLeave;
	}

	public EmployeeAndReportingDAO getEmployeeAndReportingDAO() {
		return employeeAndReportingDAO;
	}

	public void setEmployeeAndReportingDAO(
			EmployeeAndReportingDAO employeeAndReportingDAO) {
		this.employeeAndReportingDAO = employeeAndReportingDAO;
	}

	public EmployeeAndReporting getEmployeeAndReporting() {
		return employeeAndReporting;
	}

	public void setEmployeeAndReporting(
			EmployeeAndReporting employeeAndReporting) {
		this.employeeAndReporting = employeeAndReporting;
	}

	public boolean isLeaveCancelRequestApprovedAlready() {
		return leaveCancelRequestApprovedAlready;
	}

	public void setLeaveCancelRequestApprovedAlready(
			boolean leaveCancelRequestApprovedAlready) {
		this.leaveCancelRequestApprovedAlready = leaveCancelRequestApprovedAlready;
	}

	public String getLeavesMonth() {
		return leavesMonth;
	}

	public void setLeavesMonth(String leavesMonth) {
		this.leavesMonth = leavesMonth;
	}

	public List<Date> getLeaveDates() {
		return leaveDates;
	}

	public void setLeaveDates(List<Date> leaveDates) {
		this.leaveDates = leaveDates;
	}

	public float getSelectedLeaveBalance() {
		return selectedLeaveBalance;
	}

	public void setSelectedLeaveBalance(float selectedLeaveBalance) {
		this.selectedLeaveBalance = selectedLeaveBalance;
	}

	public boolean isLeaveBalanceFlag() {
		return leaveBalanceFlag;
	}

	public void setLeaveBalanceFlag(boolean leaveBalanceFlag) {
		this.leaveBalanceFlag = leaveBalanceFlag;
	}

	public float getActualBalance() {
		return actualBalance;
	}

	public void setActualBalance(float actualBalance) {
		this.actualBalance = actualBalance;
	}

	public boolean isSufficientLeaves() {
		return sufficientLeaves;
	}

	public void setSufficientLeaves(boolean sufficientLeaves) {
		this.sufficientLeaves = sufficientLeaves;
	}

	public boolean isButtonRender() {
		return buttonRender;
	}

	public void setButtonRender(boolean buttonRender) {
		this.buttonRender = buttonRender;
	}

	public List<LeaveBalance> getLeaveBalancesList() {
		return leaveBalancesList;
	}

	public void setLeaveBalancesList(List<LeaveBalance> leaveBalancesList) {
		this.leaveBalancesList = leaveBalancesList;
	}

	public boolean isRenderSLBalance() {
		return renderSLBalance;
	}

	public void setRenderSLBalance(boolean renderSLBalance) {
		this.renderSLBalance = renderSLBalance;
	}

	public boolean isRenderPLBalance() {
		return renderPLBalance;
	}

	public void setRenderPLBalance(boolean renderPLBalance) {
		this.renderPLBalance = renderPLBalance;
	}

	public boolean isRenderCLBalance() {
		return renderCLBalance;
	}

	public void setRenderCLBalance(boolean renderCLBalance) {
		this.renderCLBalance = renderCLBalance;
	}

	public boolean isRenderWHBalance() {
		return renderWHBalance;
	}

	public void setRenderWHBalance(boolean renderWHBalance) {
		this.renderWHBalance = renderWHBalance;
	}

	public boolean isRenderOHBalance() {
		return renderOHBalance;
	}

	public void setRenderOHBalance(boolean renderOHBalance) {
		this.renderOHBalance = renderOHBalance;
	}

	public LeaveTypeRole getLeaveTypeRole() {
		return leaveTypeRole;
	}

	public void setLeaveTypeRole(LeaveTypeRole leaveTypeRole) {
		this.leaveTypeRole = leaveTypeRole;
	}

	public List<LeaveTypeRole> getLeaveTypeListForRoles() {
		return leaveTypeListForRoles;
	}

	public void setLeaveTypeListForRoles(
			List<LeaveTypeRole> leaveTypeListForRoles) {
		this.leaveTypeListForRoles = leaveTypeListForRoles;
	}

	public String getAssignedLeave() {
		return assignedLeave;
	}

	public void setAssignedLeave(String assignedLeave) {
		this.assignedLeave = assignedLeave;
	}

	public boolean isAssignedSLLeaveFlag() {
		return assignedSLLeaveFlag;
	}

	public void setAssignedSLLeaveFlag(boolean assignedSLLeaveFlag) {
		this.assignedSLLeaveFlag = assignedSLLeaveFlag;
	}

	public boolean isAssignedCLLeaveFlag() {
		return assignedCLLeaveFlag;
	}

	public void setAssignedCLLeaveFlag(boolean assignedCLLeaveFlag) {
		this.assignedCLLeaveFlag = assignedCLLeaveFlag;
	}

	public boolean isAssignedWHLeaveFlag() {
		return assignedWHLeaveFlag;
	}

	public void setAssignedWHLeaveFlag(boolean assignedWHLeaveFlag) {
		this.assignedWHLeaveFlag = assignedWHLeaveFlag;
	}

	public boolean isAssignedOHLeaveFlag() {
		return assignedOHLeaveFlag;
	}

	public void setAssignedOHLeaveFlag(boolean assignedOHLeaveFlag) {
		this.assignedOHLeaveFlag = assignedOHLeaveFlag;
	}

	public boolean isAssignedPLLeaveFlag() {
		return assignedPLLeaveFlag;
	}

	public void setAssignedPLLeaveFlag(boolean assignedPLLeaveFlag) {
		this.assignedPLLeaveFlag = assignedPLLeaveFlag;
	}

	public int getColumnCount() {
		return columnCount;
	}

	public void setColumnCount(int columnCount) {
		this.columnCount = columnCount;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public boolean isLEAVETYPE_FORM_VALID() {
		return LEAVETYPE_FORM_VALID;
	}

	public void setLEAVETYPE_FORM_VALID(boolean lEAVETYPE_FORM_VALID) {
		LEAVETYPE_FORM_VALID = lEAVETYPE_FORM_VALID;
	}

	public List<EmployeeLeave> getEmployeeLeavesCancellation() {
		return employeeLeavesCancellation;
	}

	public void setEmployeeLeavesCancellation(
			List<EmployeeLeave> employeeLeavesCancellation) {
		this.employeeLeavesCancellation = employeeLeavesCancellation;
	}

	public boolean isRenderEmployeeCacelledLeaves() {
		return renderEmployeeCacelledLeaves;
	}

	public void setRenderEmployeeCacelledLeaves(
			boolean renderEmployeeCacelledLeaves) {
		this.renderEmployeeCacelledLeaves = renderEmployeeCacelledLeaves;
	}

	public boolean isSelectedLeaveBalanceRenderer() {
		return selectedLeaveBalanceRenderer;
	}

	public void setSelectedLeaveBalanceRenderer(
			boolean selectedLeaveBalanceRenderer) {
		this.selectedLeaveBalanceRenderer = selectedLeaveBalanceRenderer;
	}

	public String getSelectedLeaveType() {
		return selectedLeaveType;
	}

	public void setSelectedLeaveType(String selectedLeaveType) {
		this.selectedLeaveType = selectedLeaveType;
	}

	public Float getLopBalance() {
		return lopBalance;
	}

	public void setLopBalance(Float lopBalance) {
		this.lopBalance = lopBalance;
	}

	public boolean isAssignedLOPLeaveFlag() {
		return assignedLOPLeaveFlag;
	}

	public void setAssignedLOPLeaveFlag(boolean assignedLOPLeaveFlag) {
		this.assignedLOPLeaveFlag = assignedLOPLeaveFlag;
	}

	public boolean isRenderApplyLeaveButton() {
		return renderApplyLeaveButton;
	}

	public void setRenderApplyLeaveButton(boolean renderApplyLeaveButton) {
		this.renderApplyLeaveButton = renderApplyLeaveButton;
	}

	public boolean isRenderLeaveBalanceNotification() {
		return renderLeaveBalanceNotification;
	}

	public void setRenderLeaveBalanceNotification(
			boolean renderLeaveBalanceNotification) {
		this.renderLeaveBalanceNotification = renderLeaveBalanceNotification;
	}

	public TimeZone getDefaultTimeZone() {
		return defaultTimeZone;
	}

	public void setDefaultTimeZone(TimeZone defaultTimeZone) {
		this.defaultTimeZone = defaultTimeZone;
	}

	public Map<String, Long> getProjectManagersMap() {
		return projectManagersMap;
	}

	public void setProjectManagersMap(Map<String, Long> projectManagersMap) {
		this.projectManagersMap = projectManagersMap;
	}

	public List<Employee> getLeadEmployeesList() {
		return leadEmployeesList;
	}

	public void setLeadEmployeesList(List<Employee> leadEmployeesList) {
		this.leadEmployeesList = leadEmployeesList;
	}

	public Employee getProjectManager() {
		return projectManager;
	}

	public void setProjectManager(Employee projectManager) {
		this.projectManager = projectManager;
	}

	public EmployeeAndReporting getChangedReportingManager() {
		return changedReportingManager;
	}

	public void setChangedReportingManager(
			EmployeeAndReporting changedReportingManager) {
		this.changedReportingManager = changedReportingManager;
	}

	public long getApproverId() {
		return approverId;
	}

	public void setApproverId(long approverId) {
		this.approverId = approverId;
	}

	public Map<String, Long> getApproversMap() {
		return approversMap;
	}

	public void setApproversMap(Map<String, Long> approversMap) {
		this.approversMap = approversMap;
	}

	public Employee getApprover() {
		return approver;
	}

	public void setApprover(Employee approver) {
		this.approver = approver;
	}

	public long getNoOfDaysBetweenFromDateToDate() {
		return noOfDaysBetweenFromDateToDate;
	}

	public void setNoOfDaysBetweenFromDateToDate(
			long noOfDaysBetweenFromDateToDate) {
		this.noOfDaysBetweenFromDateToDate = noOfDaysBetweenFromDateToDate;
	}

	public boolean isIN_PROJECT() {
		return IN_PROJECT;
	}

	public void setIN_PROJECT(boolean iN_PROJECT) {
		IN_PROJECT = iN_PROJECT;
	}

	public List<Project> getProjects() {
		return projects;
	}

	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}

	public boolean isCONFIRM_FORM_VALID() {
		return CONFIRM_FORM_VALID;
	}

	public void setCONFIRM_FORM_VALID(boolean cONFIRM_FORM_VALID) {
		CONFIRM_FORM_VALID = cONFIRM_FORM_VALID;
	}

	public String getLeaveFromToBeDisplayed() {
		return leaveFromToBeDisplayed;
	}

	public void setLeaveFromToBeDisplayed(String leaveFromToBeDisplayed) {
		this.leaveFromToBeDisplayed = leaveFromToBeDisplayed;
	}

	public String getLeaveToToBeDisplayed() {
		return leaveToToBeDisplayed;
	}

	public void setLeaveToToBeDisplayed(String leaveToToBeDisplayed) {
		this.leaveToToBeDisplayed = leaveToToBeDisplayed;
	}

	public List<HolidayCalendar> getHolidaysList() {
		return holidaysList;
	}

	public void setHolidaysList(List<HolidayCalendar> holidaysList) {
		this.holidaysList = holidaysList;
	}

	public Float getCompOffBalance() {
		return compOffBalance;
	}

	public void setCompOffBalance(Float compOffBalance) {
		this.compOffBalance = compOffBalance;
	}

	public boolean isHalfDayLeaveFlag() {
		return halfDayLeaveFlag;
	}

	public void setHalfDayLeaveFlag(boolean halfDayLeaveFlag) {
		this.halfDayLeaveFlag = halfDayLeaveFlag;
	}

	public float getHalfDay() {
		return halfDay;
	}

	public void setHalfDay(float halfDay) {
		this.halfDay = halfDay;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public float getTotalInprocessDays() {
		return totalInprocessDays;
	}

	public void setTotalInprocessDays(float totalInprocessDays) {
		this.totalInprocessDays = totalInprocessDays;
	}

	public float getTotalInprocessDaysPlusCurrentNoofDays() {
		return totalInprocessDaysPlusCurrentNoofDays;
	}

	public void setTotalInprocessDaysPlusCurrentNoofDays(
			float totalInprocessDaysPlusCurrentNoofDays) {
		this.totalInprocessDaysPlusCurrentNoofDays = totalInprocessDaysPlusCurrentNoofDays;
	}

}
